package com.bodacn.keypoint;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.fragment.app.Fragment;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.ComboLineColumnChartData;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.ComboLineColumnChartView;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static com.bodacn.keypoint.MainApplication.TermNo;
import static java.lang.Math.round;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentA extends Fragment implements View.OnClickListener, View.OnLongClickListener {
    public static String TAG=FragmentB.class.getName();
    public static final int msgFocusBarcode = 1001;
    public static final int MSG_SCANBARCODE = 9001;
    public static final int MSG_GetDetail = 9002;
    public static final int MSG_DetailOver =9003;
    public static final int MSG_ChartOver =9004;
    public static final int MSG_HeadOver=9005;
    public static final int MSG_ColorSizeOver=9006;
    public static final int MSG_POOver=9007;
    public static final int MSG_ERRMSG =9008;
    public static final int MSG_AuthorMSG=9009;
    ReentrantLock reentrantLock = new ReentrantLock();
    LinearLayout mainLinerLayout;
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    SQLiteDatabase tmpdb;
    //全局变量
    PopupWindow popupWindow;
    Toast curToast;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curFactory="",curDepart,CPUID;
    Button btn_find,btn_Query,btn_SelectPO;
    ImageButton btn_editBarcode;
    TextView txt_HintInfo,txt_OrderNo,txt_StyleNo,txt_PO,txt_Color,txt_Size,txt_StyleSort,txt_Depart,txt_PSXX;
    TextView txt_DBH,txt_Barcode,txt_Number,txt_ScanNum,txt_OwenNum, txt_TodaySewNum;
    EditText edt_userno,edt_password,edt_newPassword,edt_affirmPassword;
    Button btn_AffirProc,btn_ArrangeProc,btn_Refresh,btn_DaliyAccount,btn_AttendMana;
    EditText edt_barcode;
    JSONArray resultJSON,headJSON;
    JSONArray headJson,detailJson,chartJSON;
    String PrBarcode="";

    ListView detailList;
    String  selDepartNo="",selDepart="",selOrderNo="",selStyleNo="",selPO="",selColor="",selSize="",selStyleSort="",selImageFile="",selPSXX="",selManuDepartNo="",selManuDepart="";
    EditText edt_checkReal;
    String curAuthorFunc="";
    boolean curActive=false;
    int MaxPieces=5;
    LinearLayout querylisthead;
    boolean NeedCheck=true;
    private ComboLineColumnChartView mainCTColumnChart;
    private ComboLineColumnChartData mainCTColumnData;
    GridView poGrid;
    ListView colorsizeList;
    JSONArray poJson,colorSizeJson;
    String FormType="SEW";
    private ProgressDialog waitDialog = null;
    //主程序回调传参--------------------------------------------开始;
    private FragmentACallBack mFragmentACallBack;
    /*定义一个业务接口,主程序负责实现，所以需在主程序implements中加上这个接口的引用>>>>>切记<<<<<<
    该Fragment所在Activity需要实现该接口
    该Fragment将通过此接口与它所在的Activity交互*/
    public interface FragmentACallBack {
        // 里面传个值@param Map<String,Object>适应多种类型;
        void FragmentAWorkAndTransParams(Map<String, Object> Params);
    }

    //主程序回调传参--------------------------------------------结束;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity activity = (Activity) context;
        if (!(activity instanceof FragmentACallBack)) {
            throw new IllegalStateException("MainActivity必须实现FragmentECallBack接口");
        }
        mFragmentACallBack=(FragmentACallBack) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mFragmentACallBack=null;
    }

    //图表标识
    private boolean hasAxes = true;
    private boolean hasPoints = true;
    private boolean hasLines = true;
    private boolean isCubic = false;
    private boolean hasLabels = false;
    boolean AllowScan=true;

    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean onLongClick(View view) {
        switch (view.getId()) {
            case R.id.btn_MarkBadPoint:
                MakeBadPoint("Single");
                break;
            default:
                break;
        }
        return false;
    }



    public FragmentA() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        //全局App;
        try {
            headJSON=new JSONArray("[]");
            detailJson=new JSONArray("[]");
            resultJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println(TAG+"onCreate-------------------------------------1");
        //创建适配器
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerA(new MainActivity.OnTransParamsListenerA() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        System.out.println(mParams);
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d(this.getClass().getName(),"LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curServiceDir= mParams.get("ServiceDir").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            curFactory=mParams.get("Factory").toString();
                            CPUID=mParams.get("CPUID").toString();
                            Log.d(this.getClass().getName(),"LoginParam------------------>2");
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if ((paramComm=="RefreshDetail")&&curActive){
                            refreshChart( "ManuInfo",FormType);
                        }
                        if ((paramComm=="Barcode")&&curActive){
                            String barcode=mParams.get("Barcode").toString();
                            edt_barcode.setText(barcode);
                            searchBarcodeData(barcode);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        System.out.println(TAG+"onCreate-------------------------------------2");
    }

    //提交所选择的工序至服务器,然后刷新工序列表;
    private void GetHeadList(final String paramType,final String paramFormName) {
        try {
            headJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Runnable run = new Runnable() {
            @Override
            public void run() {
                //将数据读到JSONArray;
                try {
                    String sqlcmd="Exec KeyPoint_CustomGetHead @OperType='Title',@QueryType='"+paramType+"',@FormName='"+paramFormName
                            +"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
                    Statement stmt = DBUtil.getSQLConnection().createStatement();
                    ResultSet rs = stmt.executeQuery(sqlcmd);
                    //取字段相关信息;
                    ResultSetMetaData metaData = rs.getMetaData();
                    int columnCount = metaData.getColumnCount();
                    //遍列数据;
                    while (rs.next()) {
                        JSONObject jsonObj = new JSONObject();
                        // 遍历每一列
                        for (int i = 1; i <= columnCount; i++) {
                            String columnName = metaData.getColumnLabel(i);
                            Object value = rs.getObject(columnName);
                            if (value==null) value="";
                            jsonObj.put(columnName, value);
                        }
                        headJson.put(jsonObj);
                    }
                    //显示预排单;
                    Message msg = new Message();
                    msg.what = MSG_HeadOver;
                    fragmentHandler.removeMessages(msg.what);
                    fragmentHandler.sendMessage(msg);
                    //消息给创建列;
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }catch (Exception e){
                    e.printStackTrace();
                }


            }
        };
        new Thread(run).start();
    }
    //自动刷新数据
    private void refreshChart(String paramType,String paramFormName) {
        System.out.println(TAG+":准备刷新明细图表");
        String sqlcmd="Exec KeyPoint_GetChart @OperType='Chart',@QueryType='"+paramType+"',@FormName='"+paramFormName
                +"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlcmd);
    }

    /**
     *
     */
    //显示图表;
    private void showBalanceChart()
    {
        Log.d(TAG,"showBalanceChart()----------------------------------------------------->1");
        int reindex=0;
        float WorkCT=100;
        //初始化工序列表;
        List<AxisValue> axisValues = new ArrayList<AxisValue>();
        List<Column> columns = new ArrayList<Column>();
        List<SubcolumnValue> subcolValues;
        List<Line> lines = new ArrayList<Line>();
        List<PointValue> aPointValues=new ArrayList<PointValue>();
        List<PointValue> aLineValues=new ArrayList<PointValue>();
        try {
            for (int i=0;i<chartJSON.length();i++){
                String colLable=chartJSON.optJSONObject(i).getString("TitleCaption");
                float colValue=chartJSON.optJSONObject(i).getLong("ColValue");
                float lineValue=chartJSON.optJSONObject(i).getLong("LineValue");
                //多个子柱对比时可加多个值;
                subcolValues=new ArrayList<SubcolumnValue>();
                subcolValues.add(new SubcolumnValue(colValue, ChartUtils.COLORS[0]));
                //添加列并在柱子上方加值显示;不仅仅是在选择时显示;
                columns.add(new Column(subcolValues).setHasLabelsOnlyForSelected(true).setHasLabels(true));
                aPointValues.add(new PointValue(i, lineValue));
                //X轴标签;
                axisValues.add(new AxisValue(i).setLabel(colLable));
                reindex++;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.d(TAG,"showBalanceChart()----------------------------------------------------->2");
        //创建柱状图数据;
        ColumnChartData columnChartData = new ColumnChartData(columns);
        //线条图
        Line line = new Line(aPointValues);
        line.setColor(ChartUtils.COLORS[1]);
        line.setCubic(isCubic);
        line.setHasLabels(hasLabels);
        line.setHasLines(hasLines);
        line.setHasPoints(false);
        lines.add(line);
        //创建线形数据;
        LineChartData lineChartData = new LineChartData(lines);
        //创建图形数据;
        mainCTColumnData=new ComboLineColumnChartData(columnChartData, lineChartData);
        //国形控制格式;
        if (hasAxes) {
            Axis axisX = new Axis();
            Axis axisY = new Axis().setHasLines(true);
            axisX.setName("时间段");
            axisY.setName("产量");
            axisY.setLineColor(getResources().getColor(R.color.linebackcolor));
            axisX.setHasTiltedLabels(true);
            axisX.setHasSeparationLine(false);
            axisX.setValues(axisValues);
            axisY.setTextColor(getResources().getColor(R.color.text_main));
            axisX.setTextColor(getResources().getColor(R.color.text_main));
            mainCTColumnData.setAxisXBottom(axisX);
            mainCTColumnData.setAxisYLeft(axisY);
        } else {
            mainCTColumnData.setAxisXBottom(null);
            mainCTColumnData.setAxisYLeft(null);
        }
        //显示图表;
        mainCTColumnChart.setComboLineColumnChartData(mainCTColumnData);
        //仅横向允许放大;
        mainCTColumnChart.setValueSelectionEnabled(false);
        mainCTColumnChart.setZoomEnabled(false);
        mainCTColumnChart.setZoomType(ZoomType.HORIZONTAL);
        //判断是否有数据，如果无数据，则调用数据刷新;
    }

    //创建列;
    private void CreateListHead() {
        //内容为表头，宽度，自适应;
        if ((headJson != null) && (headJson.length() > 0)) {
            int childCount = querylisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = querylisthead.getChildAt(i);
                if ((view instanceof TextView)||(view instanceof View)) {
                    querylisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            System.out.println(headJson);
            for (int i=0;i<headJson.length();i++)
                if (headJson.optJSONObject(i).has("TitleText") == true) {
                    try {
                        TitleName = headJson.optJSONObject(i).getString("TitleName");
                        TitleText = headJson.optJSONObject(i).getString("TitleText");
                        TxtSize = headJson.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJson.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJson.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(getContext());
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.text_main));
                        tv.setTextSize(TxtSize);
                        if (headJson.optJSONObject(i).has("Align")==true) {
                            Align = headJson.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJson.optJSONObject(i).has("TitleColor")==true){
                            tv.setTextColor(GetColorValue( headJson.optJSONObject(i).getString("TitleColor")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) querylisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else querylisthead.addView(tv);
                        //增加间隔线
                        if (i<headJson.length()-1) {
                            View lineView = new View(getContext());
                            lineView.setBackgroundColor(getResources().getColor(R.color.gridLine));
                            querylisthead.addView(lineView, new LinearLayout.LayoutParams(1, MATCH_PARENT, 0));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            querylisthead.postInvalidate();
            //发消息查明细;
            Message msg = new Message();
            msg.what = MSG_GetDetail;
            fragmentHandler.removeMessages(msg.what);
            fragmentHandler.sendMessage(msg);
        }
    }
    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    //设置焦点到扫描输入框
    private void setEditBarcodeFocus()
    {
        //传消息给主界面;
        if (mFragmentACallBack!=null)
        {
            fragmentParams.clear();
            fragmentParams.put("ParamComm","AllowScan");//命令;
            fragmentParams.put("ParamValue","Y");//参数;
            mFragmentACallBack.FragmentAWorkAndTransParams(fragmentParams);
        } else Log.d("msg","mFragmentECallBack-----------空的咋办");
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        if (edt_barcode!=null) {
            edt_barcode.selectAll();
            edt_barcode.setFocusable(true);
            edt_barcode.setFocusableInTouchMode(true);
            edt_barcode.requestFocus();
            edt_barcode.requestFocusFromTouch();
            hideIM(getView());
            hideBottomUIMenu();
        }
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_a, container, false);
        InitView(root);
        System.out.println(this.getClass().getName()+"_onCreateView");
        return root;
    }
    //初始化;
    public void InitView(View view){
        //提示框pd=new ProgressDialog(this);
        view.findViewById(R.id.btn_TargetNum).setOnClickListener(this);
        view.findViewById(R.id.btn_WorkPeople).setOnClickListener(this);
        view.findViewById(R.id.btn_cloth_piece_check).setOnClickListener(this);
        mainLinerLayout=view.findViewById(R.id.mainLinerLayout);
        waitDialog= new ProgressDialog(getContext());
        waitDialog.setTitle(getString(R.string.SystemHint));
        btn_find=(Button)view.findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_SelectPO=view.findViewById(R.id.btn_SelectPO);
        btn_SelectPO.setOnClickListener(this);
        btn_Query=(Button)view.findViewById(R.id.btn_Query);
        btn_Query.setOnClickListener(this);
        btn_editBarcode=(ImageButton)view.findViewById(R.id.btn_editBarcode);
        btn_editBarcode.setOnClickListener(this);
        btn_editBarcode.setFocusable(false);
        btn_editBarcode.setFocusableInTouchMode(false);
        txt_PSXX=view.findViewById(R.id.txt_PSXX);
        view.findViewById(R.id.btn_ManuPlan).setOnClickListener(this);
        view.findViewById(R.id.btn_QueryOut).setOnClickListener(this);
        btn_AttendMana=view.findViewById(R.id.btn_AttendMana);
        //界面Edit;
        edt_barcode=(EditText)view.findViewById(R.id.edt_barcode);
        edt_barcode.setInputType(InputType.TYPE_NULL);
        edt_barcode.requestFocus();
        edt_barcode.requestFocusFromTouch();
        view.findViewById(R.id.btn_Mate).setOnClickListener(this);
        /*
        edt_barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        hideIM(v);
                        if (edt_barcode.getText().length()==0) {
                            curToast.setText(getString(R.string.PleaseInputBarcode));
                            curToast.show();
                        } else {
                            searchBarcodeData(edt_barcode.getText().toString());
                        }
                        //未有焦点
                        if (edt_barcode.isFocused()==false){
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        } else edt_barcode.selectAll();
                    }

                }
                return false;
            }
        });
         */
        txt_HintInfo=view.findViewById(R.id.txt_HintInfo);
        txt_OrderNo=view.findViewById(R.id.txt_OrderNo);
        txt_StyleNo=view.findViewById(R.id.txt_StyleNo);
        txt_PO=view.findViewById(R.id.txt_PO);
        txt_Color=view.findViewById(R.id.txt_Color);
        txt_Size=view.findViewById(R.id.txt_Size);
        txt_StyleSort=view.findViewById(R.id.txt_StyleSort);
        txt_Depart=view.findViewById(R.id.txt_Depart);
        txt_DBH=view.findViewById(R.id.txt_DBH);
        txt_Barcode=view.findViewById(R.id.txt_Barcode);
        txt_Number=view.findViewById(R.id.txt_Number);
        txt_ScanNum=view.findViewById(R.id.txt_ScanNum);
        txt_OwenNum=view.findViewById(R.id.txt_OwenNum);
        txt_TodaySewNum =view.findViewById(R.id.txt_TodaySewNum);
        //三个按钮
        btn_AffirProc=view.findViewById(R.id.btn_AffirProc);
        btn_AffirProc.setOnClickListener(this);
        btn_ArrangeProc=view.findViewById(R.id.btn_ArrangeProc);
        btn_ArrangeProc.setOnClickListener(this);
        btn_DaliyAccount=view.findViewById(R.id.btn_DaliyAccount);
        btn_DaliyAccount.setOnClickListener(this);
        btn_Refresh=view.findViewById(R.id.btn_Refresh);
        btn_Refresh.setOnClickListener(this);
        detailList=view.findViewById(R.id.colorsizeList);
        view.findViewById(R.id.btn_AttendMana).setOnClickListener(this);
        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);
        //curToast.setGravity(Gravity.CENTER, 0, 0);
        //列表头;
        querylisthead=view.findViewById(R.id.querylisthead);
        mainCTColumnChart=view.findViewById(R.id.mainCTColumnChart);
        if (MainApplication.DaliyPower.equals("Y")) {
            if (MainApplication.CheckFactory.equals("0")) {
                btn_DaliyAccount.setVisibility(View.VISIBLE);
                btn_ArrangeProc.setVisibility(View.VISIBLE);
                btn_AttendMana.setVisibility(View.VISIBLE);
                btn_AffirProc .setVisibility(View.VISIBLE);
            }
            else {
                btn_DaliyAccount.setVisibility(View.GONE);
                btn_ArrangeProc.setVisibility(View.GONE);
                btn_AttendMana.setVisibility(View.GONE);
                btn_AffirProc .setVisibility(View.GONE);
            }
        }
        else {
            btn_DaliyAccount.setVisibility(View.GONE);
            btn_ArrangeProc.setVisibility(View.GONE);
            btn_AttendMana.setVisibility(View.GONE);
            btn_AffirProc .setVisibility(View.GONE);
        }

    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getActivity(), notification);
        r.play();

    }

    @Override
    public void onResume() {
        super.onResume();
        GetHeadList("WorkDetail",FormType);
        refreshChart( "ManuInfo",FormType);
        hideBottomUIMenu();
    }


    //刷新缸布列表;
    private void searchBarcodeData(String BarcodeParam)
    {
        NeedCheck=true;
        if (selDepart.length()==0) {
            selDepart=curDepart;
            selDepartNo=curDepartNo;
        }
        if (AllowScan==true) {
            AllowScan = false;
            String SqlComm = "Exec KeyPoint_SewOnScan @Barcode='" + BarcodeParam + "',@OrderNo='" + txt_OrderNo.getText().toString() + "',@StyleNo='" + txt_StyleNo.getText().toString() + "',@StyleSort='" + txt_StyleSort.getText().toString()
                    + "',@PSXX='" + txt_PSXX.getText().toString() + "',@Color='" + txt_Color.getText().toString() + "',@Size='" + txt_Size.getText().toString() + "',@PO='" + txt_PO.getText().toString() + "',@DepartNo='" + selDepartNo + "',@ManuDepartNo='" + selManuDepartNo
                    + "',@OPERTYPE='SCANBARCODE',@UserNo='" + curLoginUserNo  + "',@CPUID='" + CPUID + "',@TermNo='"+ TermNo +"'";
            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm);
            //执行SQL过程
            PrBarcode = BarcodeParam;
        }
    }


    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        Intent tmpintent;
        Bundle paramBundle = new Bundle();
        switch (v.getId()){
            //衣片复核
            case R.id.btn_cloth_piece_check:
                Intent outIntent1=new Intent(getContext(),ClothPieceCheckActivity.class);
                paramBundle.clear();
                paramBundle.putString("CurDepartNo",curDepartNo);
                paramBundle.putString("LoginUserNo", curLoginUserNo);
                outIntent1.putExtras(paramBundle);
                startActivity(outIntent1);
                break;
            case R.id.btn_Mate:
                Intent mateintent=new Intent(getContext(),MateActivity.class);
                paramBundle.clear();
                paramBundle.putString("LoginUserNo", curLoginUserNo);
                paramBundle.putString("LoginUser",curLoginUser);
                paramBundle.putString("CurDepartNo",curDepartNo);
                paramBundle.putString("CurDepart",curDepart);
                paramBundle.putString("CurFactory",curFactory);
                paramBundle.putString("ServiceUrl",curServiceUrl);
                paramBundle.putString("ServiceDir",curServiceDir);
                paramBundle.putString("OrderNo",txt_OrderNo.getText().toString());
                paramBundle.putString("StyleNo",txt_StyleNo.getText().toString());
                paramBundle.putString("StyleSort",txt_StyleSort.getText().toString());
                paramBundle.putString("Color",txt_Color.getText().toString());
                paramBundle.putString("Size",txt_Size.getText().toString());
                paramBundle.putString("PO",txt_PO.getText().toString());
                paramBundle.putString("CPUID",CPUID);
                mateintent.putExtras(paramBundle);
                startActivity(mateintent);
                break;
            case R.id.btn_AttendMana:
                tmpintent=new Intent(getContext(),AttendActivity.class);
                paramBundle.clear();
                paramBundle.putString("LoginUserNo", curLoginUserNo);
                paramBundle.putString("LoginUser",curLoginUser);
                paramBundle.putString("CurDepartNo",curDepartNo);
                paramBundle.putString("CurDepart",curDepart);
                paramBundle.putString("CurFactory",curFactory);
                paramBundle.putString("ServiceUrl",curServiceUrl);
                paramBundle.putString("ServiceDir",curServiceDir);
                paramBundle.putString("CPUID",CPUID);
                tmpintent.putExtras(paramBundle);
                startActivity(tmpintent);
                break;
            case R.id.btn_ManuPlan:
                tmpintent=new Intent(getContext(),ManuplanActivity.class);
                paramBundle.clear();
                paramBundle.putString("LoginUserNo", curLoginUserNo);
                paramBundle.putString("LoginUser",curLoginUser);
                paramBundle.putString("CurDepartNo",curDepartNo);
                paramBundle.putString("CurDepart",curDepart);
                paramBundle.putString("CurFactory",curFactory);
                paramBundle.putString("ServiceUrl",curServiceUrl);
                paramBundle.putString("ServiceDir",curServiceDir);
                paramBundle.putString("CPUID",CPUID);
                paramBundle.putString("QueryTitle", "生产计划");
                paramBundle.putString("OrderNo",txt_OrderNo.getText().toString());
                paramBundle.putString("StyleNo",txt_StyleNo.getText().toString());
                paramBundle.putString("StyleSort",txt_StyleSort.getText().toString());
                paramBundle.putString("NeedOrder","YES");
                tmpintent.putExtras(paramBundle);
                startActivity(tmpintent);
                break;
            case R.id.btn_QueryOut:
                Intent outIntent=new Intent(getContext(),OutputActivity.class);
                paramBundle.clear();
                paramBundle.putString("LoginUserNo", curLoginUserNo);
                paramBundle.putString("LoginUser",curLoginUser);
                paramBundle.putString("CurDepartNo",curDepartNo);
                paramBundle.putString("CurDepart",curDepart);
                paramBundle.putString("CurFactory",curFactory);
                paramBundle.putString("ServiceUrl",curServiceUrl);
                paramBundle.putString("ServiceDir",curServiceDir);
                paramBundle.putString("CPUID",CPUID);
                paramBundle.putString("QueryTitle", "投缝查询");
                paramBundle.putString("OrderNo",txt_OrderNo.getText().toString());
                paramBundle.putString("StyleNo",txt_StyleNo.getText().toString());
                paramBundle.putString("StyleSort",txt_StyleSort.getText().toString());
                paramBundle.putString("NeedOrder","NO");
                outIntent.putExtras(paramBundle);
                startActivity(outIntent);
                break;

            case R.id.btn_SelectPO:
                if ((txt_Depart.getText().toString().length()>0)&&(txt_OrderNo.getText().toString().length()>0)) {
                    waitDialog.setMessage("正在拉取PO列表.....");
                    waitDialog.show();
                    GetPO(selDepart, selOrderNo, selStyleNo, selStyleSort, selManuDepartNo);
                } else {
                    curToast.setText("请先刷条码！");
                    curToast.show();
                };
                break;
            case R.id.btn_Query:
                Intent tmpQueryIntent=new Intent(getContext(),QueryActivity.class);
                paramBundle.clear();
                paramBundle.putString("LoginUserNo", curLoginUserNo);
                paramBundle.putString("LoginUser",curLoginUser);
                paramBundle.putString("CurDepartNo",curDepartNo);
                paramBundle.putString("CurDepart",curDepart);
                paramBundle.putString("CurFactory",curFactory);
                paramBundle.putString("ServiceUrl",curServiceUrl);
                paramBundle.putString("ServiceDir",curServiceDir);
                paramBundle.putString("CPUID",CPUID);
                paramBundle.putString("QueryTitle", "缝制扫描情况");
                paramBundle.putString("OrderNo",txt_OrderNo.getText().toString());
                paramBundle.putString("StyleNo",txt_StyleNo.getText().toString());
                paramBundle.putString("StyleSort",txt_StyleSort.getText().toString());
                paramBundle.putString("NeedOrder","YES");
                tmpQueryIntent.putExtras(paramBundle);
                startActivity(tmpQueryIntent);
                break;
            case R.id.btn_editBarcode:
                edt_barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edt_barcode,InputMethodManager.SHOW_FORCED);
                break;
            case R.id.btn_find:
                if (edt_barcode.getText().length()>0){
                    searchBarcodeData(edt_barcode.getText().toString());
                } else {
                    curToast.setText("请先输入条码!");
                    curToast.show();
                    return;
                }
                break;
            case R.id.btn_Refresh:
                GetDetail("WorkDetail",FormType);
                break;
            case R.id.view_oneBtn:
            case R.id.view_twoBtn:
            case R.id.view_threeBtn:
            case R.id.view_fourBtn:
            case R.id.view_fiveBtn:
            case R.id.view_sixBtn:
            case R.id.view_sevenBtn:
            case R.id.view_eightBtn:
            case R.id.view_nineBtn:
            case R.id.view_zeroBtn:
                Button tmpBtn1 = v.findViewById(v.getId());
                edt_checkReal.getText().append(tmpBtn1.getText());
                break;
            case R.id.view_delBtn:
                if (edt_checkReal.getText().length() > 0) {
                    edt_checkReal.setSelection(edt_checkReal.getText().length());
                    int start = edt_checkReal.getSelectionStart();
                    edt_checkReal.getText().delete(start - 1, start);
                }
                break;
            case R.id.view_pointBtn:
                System.out.println("AindexOf:" + edt_checkReal.getText().toString().indexOf("."));
                if ((edt_checkReal.getText().toString().indexOf(".") == -1)&&(edt_checkReal.getText().toString().indexOf("/") == -1)) {
                    edt_checkReal.getText().append(".");
                }
                break;
            case R.id.view_clearBtn:
                edt_checkReal.setText("");
                break;
            case R.id.btn_AffirProc:
                curAuthorFunc="AffirProc";
                showPassword("工序管理");
                break;
            case R.id.btn_ArrangeProc:
                curAuthorFunc="ArrangeProc";
                showPassword("工序预排");
                break;
            case R.id.btn_DaliyAccount:
                curAuthorFunc="DaliyAccount";
                showPassword("每日报帐");
                break;
            case R.id.btn_PswAffirm:
                LoginCheck(curAuthorFunc);
                break;
            case R.id.btn_PswSave:
                SavePassword();
                break;
            case R.id.btn_TargetNum:
                curAuthorFunc="TargetNum";
                showEditNum("目标产量设定");
                break;
            case R.id.btn_WorkPeople:
                curAuthorFunc="WorkPeople";
                showEditNum("工作人数设定");
                break;
            case R.id.btn_numAffirm:
                NumAffirmTrans(curAuthorFunc);
                break;
            default:
                break;
        }
    }

    private void NumAffirmTrans(String paramFunc) {
        //执行SQL过程
        String SqlComm = "Exec KeyPoint_NumTrans @OperType='AffirmTrans',@FuncName='" + paramFunc  + "',@FormType='" + FormType+ "',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
        if (popupWindow.isShowing()) popupWindow.dismiss();
    }

    private void showAffirmActivity(){
        System.out.println("Enter showAffirmActivity");
        Intent affirmActivity=new Intent(getContext(),AffirmActivity.class);
        Bundle paramBundle = new Bundle();
        paramBundle.clear();
        paramBundle.putString("LoginUserNo", curLoginUserNo);
        paramBundle.putString("LoginUser",curLoginUser);
        paramBundle.putString("CurDepartNo",curDepartNo);
        paramBundle.putString("CurDepart",curDepart);
        paramBundle.putString("CurFactory",curFactory);
        paramBundle.putString("ServiceUrl",curServiceUrl);
        paramBundle.putString("ServiceDir",curServiceDir);
        paramBundle.putString("CPUID",CPUID);
        paramBundle.putString("WorkSection", FormType);
        paramBundle.putString("NeedOrder","YES");
        paramBundle.putString("QueryTitle","缝制积分确认");
        affirmActivity.putExtras(paramBundle);
        startActivity(affirmActivity);
    }

    private void showProcActivity(){
        Intent intentProcActivity=new Intent(getContext(),ProcActivity.class);
        Bundle procBundle = new Bundle();
        procBundle.clear();
        procBundle.putString("LoginUserNo", curLoginUserNo);
        procBundle.putString("LoginUser",curLoginUser);
        procBundle.putString("CurDepartNo",curDepartNo);
        procBundle.putString("CurDepart",curDepart);
        procBundle.putString("CurFactory",curFactory);
        procBundle.putString("ServiceUrl",curServiceUrl);
        procBundle.putString("ServiceDir",curServiceDir);
        procBundle.putString("CPUID",CPUID);
        procBundle.putString("WorkSection", FormType);
        procBundle.putString("OrderNo",txt_OrderNo.getText().toString());
        procBundle.putString("StyleNo",txt_StyleNo.getText().toString());
        procBundle.putString("StyleSort",txt_StyleSort.getText().toString());
        procBundle.putString("NeedOrder","YES");
        intentProcActivity.putExtras(procBundle);
        startActivity(intentProcActivity);
    }


    private void showWorkActivity(){
        Intent workActivity=new Intent(getContext(),WorkActivity.class);
        Bundle workBundle = new Bundle();
        workBundle.clear();
        workBundle.putString("LoginUserNo", curLoginUserNo);
        workBundle.putString("LoginUser",curLoginUser);
        workBundle.putString("CurDepartNo",curDepartNo);
        workBundle.putString("CurDepart",curDepart);
        workBundle.putString("CurFactory",curFactory);
        workBundle.putString("ServiceUrl",curServiceUrl);
        workBundle.putString("ServiceDir",curServiceDir);
        workBundle.putString("CPUID",CPUID);
        workBundle.putString("WorkSection", FormType);
        workBundle.putString("OrderNo",txt_OrderNo.getText().toString());
        workBundle.putString("StyleNo",txt_StyleNo.getText().toString());
        workBundle.putString("StyleSort",txt_StyleSort.getText().toString());
        workBundle.putString("NeedOrder","YES");
        workBundle.putString("QueryTitle","投缝报帐查询");

        workActivity.putExtras(workBundle);
        startActivity(workActivity);
    }
    private void LoginCheck(String paramFunc) {
        if (edt_userno.getText().toString().length()>0&&edt_password.getText().toString().length()>0) {
            System.out.println("Enter LoginCheck-1");
            //执行SQL过程
            String SqlComm = "Exec KeyPoint_AuthorCheck @OperType='AuthorCheck',@FuncName='" + paramFunc + "',@AuthorNo='" + edt_userno.getText().toString() + "',@Password='" + edt_password.getText().toString() + "',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm);
        }else{
            AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                    .setTitle("系统提示").setMessage("请输入用户名密码进行授权!")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            hideBottomUIMenu();
                            return;
                        }
                    }).create(); // 创建对话框
            alertDialog.show(); // 显示对话框
        }
    }

    private void SavePassword() {
        if (edt_affirmPassword.getText().toString().equals(edt_newPassword.getText().toString())) {
            //执行SQL过程
            String SqlComm = "Exec KeyPoint_AuthorChangePsw @OperType='ChangePsw',@AuthorNo='" + edt_userno.getText().toString() + "',@Password='" + edt_password.getText().toString()
                    + "',@NewPassword='" + edt_newPassword.getText().toString() + "',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm);
        } else{
            AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                    .setTitle("系统提示").setMessage("新密码同确认密码不一致,请检查!")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            hideBottomUIMenu();
                            return;
                        }
                    }).create(); // 创建对话框
            alertDialog.show(); // 显示对话框
        }
    }

    //修改包件数;
    private void showPassword(String paramFunc){
        //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
        View view = LayoutInflater.from(getContext()).inflate(R.layout.input_password, null);
        popupWindow = new PopupWindow(view,200,300);//参数为1.View 2.宽度 3.高度
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);//设置点击外部区域可以取消popupWindow
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        ((TextView)view.findViewById(R.id.tv_pop_title)).setText(paramFunc+"登陆授权");
        view.findViewById(R.id.view_oneBtn).setOnClickListener(this);
        view.findViewById(R.id.view_twoBtn).setOnClickListener(this);
        view.findViewById(R.id.view_threeBtn).setOnClickListener(this);
        view.findViewById(R.id.view_fourBtn).setOnClickListener(this);
        view.findViewById(R.id.view_fiveBtn).setOnClickListener(this);
        view.findViewById(R.id.view_sixBtn).setOnClickListener(this);
        view.findViewById(R.id.view_sevenBtn).setOnClickListener(this);
        view.findViewById(R.id.view_eightBtn).setOnClickListener(this);
        view.findViewById(R.id.view_nineBtn).setOnClickListener(this);
        view.findViewById(R.id.view_zeroBtn).setOnClickListener(this);
        view.findViewById(R.id.view_delBtn).setOnClickListener(this);
        view.findViewById(R.id.view_clearBtn).setOnClickListener(this);
        view.findViewById(R.id.btn_PswAffirm).setOnClickListener(this);
        view.findViewById(R.id.btn_PswSave).setOnClickListener(this);
        edt_userno=view.findViewById(R.id.edt_userno);
        edt_userno.setText(curLoginUserNo);
        edt_userno.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edt_checkReal.setBackground(null);
                edt_checkReal =edt_userno;
                edt_checkReal.setBackgroundColor(getResources().getColor(R.color.lightskyblue));
            }
        });
        edt_password=view.findViewById(R.id.edt_password);
        edt_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edt_checkReal.setBackground(null);
                edt_checkReal =edt_password;
                edt_checkReal.setBackgroundColor(getResources().getColor(R.color.lightskyblue));
            }
        });
        edt_newPassword=view.findViewById(R.id.edt_newPassword);
        edt_newPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edt_checkReal.setBackground(null);
                edt_checkReal =edt_newPassword;
                edt_checkReal.setBackgroundColor(getResources().getColor(R.color.lightskyblue));
            }
        });
        edt_affirmPassword=view.findViewById(R.id.edt_affirmPassword);
        edt_affirmPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edt_checkReal.setBackground(null);
                edt_checkReal =edt_affirmPassword;
                edt_checkReal.setBackgroundColor(getResources().getColor(R.color.lightskyblue));
            }
        });
        edt_checkReal=edt_password;
        edt_checkReal.setBackgroundColor(getResources().getColor(R.color.lightskyblue));
        //控制屏幕宽度
        int deviationX=700,deviationY=410;
        DisplayMetrics dm = new DisplayMetrics();
        popupWindow.setWidth(dp2px(deviationX));
        popupWindow.setHeight(dp2px(deviationY));
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAtLocation(mainLinerLayout,Gravity.CENTER,0,0);

    }

    //修改包件数;
    private void showEditNum(String paramFunc){
        //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
        View view = LayoutInflater.from(getContext()).inflate(R.layout.input_numkey, null);
        popupWindow = new PopupWindow(view,200,300);//参数为1.View 2.宽度 3.高度
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);//设置点击外部区域可以取消popupWindow
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        ((TextView)view.findViewById(R.id.tv_pop_title)).setText(paramFunc);
        System.out.println("A--1");
        view.findViewById(R.id.view_oneBtn).setOnClickListener(this);
        view.findViewById(R.id.view_twoBtn).setOnClickListener(this);
        view.findViewById(R.id.view_threeBtn).setOnClickListener(this);
        view.findViewById(R.id.view_fourBtn).setOnClickListener(this);
        view.findViewById(R.id.view_fiveBtn).setOnClickListener(this);
        view.findViewById(R.id.view_sixBtn).setOnClickListener(this);
        view.findViewById(R.id.view_sevenBtn).setOnClickListener(this);
        view.findViewById(R.id.view_eightBtn).setOnClickListener(this);
        view.findViewById(R.id.view_nineBtn).setOnClickListener(this);
        view.findViewById(R.id.view_zeroBtn).setOnClickListener(this);
        view.findViewById(R.id.view_delBtn).setOnClickListener(this);
        view.findViewById(R.id.view_clearBtn).setOnClickListener(this);
        view.findViewById(R.id.btn_numAffirm).setOnClickListener(this);
        edt_checkReal=view.findViewById(R.id.edt_checkReal);
        edt_checkReal.setBackgroundColor(getResources().getColor(R.color.lightskyblue));
        System.out.println("A--4");
        //控制屏幕宽度
        int deviationX=600,deviationY=350;
        DisplayMetrics dm = new DisplayMetrics();
        popupWindow.setWidth(dp2px(deviationX));
        popupWindow.setHeight(dp2px(deviationY));
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAtLocation(mainLinerLayout,Gravity.CENTER,0,0);

    }
    //dp 转换成px
    public int dp2px(float dp)
    {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }

    //显示工序选择
    private void selectPO(){
        selOrderNo=txt_OrderNo.getText().toString();
        selStyleNo=txt_StyleNo.getText().toString();
        selStyleSort=txt_StyleSort.getText().toString();
        selPO=txt_PO.getText().toString();
        selColor=txt_Color.getText().toString();
        selSize=txt_Size.getText().toString();
        //创建布局
        LayoutInflater inflater=getActivity().getLayoutInflater();
        final View proc_stylefind=inflater.inflate(R.layout.select_sew_po, null);
        TextView tv_OrderNo=proc_stylefind.findViewById(R.id.txt_OrderNo);
        TextView tv_StyleNo=proc_stylefind.findViewById(R.id.txt_StyleNo);
        TextView tv_StyleSort=proc_stylefind.findViewById(R.id.txt_StyleSort);
        final TextView tv_Color=proc_stylefind.findViewById(R.id.txt_Color);
        final TextView tv_PO=proc_stylefind.findViewById(R.id.txt_PO);
        final TextView tv_Size=proc_stylefind.findViewById(R.id.txt_Size);
        tv_OrderNo.setText(selOrderNo);
        tv_StyleNo.setText(selStyleNo);
        tv_StyleSort.setText(selStyleSort);
        tv_Color.setText(selColor);
        tv_PO.setText(selPO);
        tv_Size.setText(selSize);
        poGrid=proc_stylefind.findViewById(R.id.poGrid);
        poGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                try {
                    selPO=poJson.optJSONObject(i).getString("PO");
                    selColor="";
                    selSize="";
                    selPSXX="";
                    tv_PO.setText(selPO);
                    tv_Color.setText(selColor);
                    tv_Size.setText(selColor);
                    GetColorSize(selDepart,selOrderNo,selStyleNo,selStyleSort,selPO,selManuDepartNo);
                } catch (JSONException e) {
                    e.printStackTrace();
                    curToast.setText(e.getMessage());
                    curToast.show();
                }
            }
        });
        colorsizeList=proc_stylefind.findViewById(R.id.colorsizeList);
        colorsizeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                view.setSelected(true);
                try {
                    selColor=colorSizeJson.optJSONObject(i).getString("Color");
                    selSize=colorSizeJson.optJSONObject(i).getString("Size");
                    selPSXX=colorSizeJson.optJSONObject(i).getString("PSXX");
                    tv_Color.setText(selColor);
                    tv_Size.setText(selColor);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //显示明细数据
        if (poGrid!=null) {
            POGridAdapter poGridAdapter = new POGridAdapter(getContext());
            poGrid.setAdapter(poGridAdapter);
        }
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(proc_stylefind).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (selColor.length()>0) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set(dialog,true );
                                txt_PO.setText(selPO);
                                txt_Size.setText(selSize);
                                txt_Color.setText(selColor);
                                txt_Depart.setText(selManuDepart);
                                txt_PSXX.setText(selPSXX);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }

                        } else {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set( dialog,false );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText("请通过点击选中需要查询的款式！");
                            curToast.show();
                        }
                    }
                }
        ).setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Field field = null;
                try {
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        });
        final AlertDialog alterDialog =builder.create();
        alterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //禁止两个按键上获取焦点，不然扫描框里就会失去焦点,在OnShow之前;
                System.out.println("alterDialog-setOnShowListener");
            }
        });
        alterDialog.show();
        //此处设置位置窗体大小
        WindowManager.LayoutParams params = alterDialog.getWindow().getAttributes();
        params.width = 900;
        params.height = 600 ;
        alterDialog.getWindow().setAttributes(params);

    }


    //订单表格适配器;
    public final class POGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public POGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return poJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return poJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_style_poitem, null, false);
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if ((poJson.optJSONObject(position).has("PO") == true)&&(view.findViewById(R.id.item_PO)!=null)) {
                    ((TextView) view.findViewById(R.id.item_PO)).setText(poJson.optJSONObject(position).getString("PO"));
                    //((TextView) view.findViewById(R.id.item_DepartNo)).setTextColor(color);
                }

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","POGridAdapter_position:"+position);
            return view;
        }
    }


    //订单表格适配器;
    public final class ColorSizeListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ColorSizeListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return colorSizeJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return colorSizeJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.select_sew_po_colorhead, null, false);
            int pullVatListWidth=parent.getWidth();
            //view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (colorSizeJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = colorSizeJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                if ((colorSizeJson.optJSONObject(position).has("PSXX") == true)&&(view.findViewById(R.id.item_PSXX)!=null)) {
                    ((TextView) view.findViewById(R.id.item_PSXX)).setText(colorSizeJson.optJSONObject(position).getString("PSXX"));
                    ((TextView) view.findViewById(R.id.item_PSXX)).setTextColor(color);
                }

                if ((colorSizeJson.optJSONObject(position).has("Color") == true)&&(view.findViewById(R.id.item_Color)!=null)) {
                    ((TextView) view.findViewById(R.id.item_Color)).setText(colorSizeJson.optJSONObject(position).getString("Color"));
                    ((TextView) view.findViewById(R.id.item_Color)).setTextColor(color);
                }
                if ((colorSizeJson.optJSONObject(position).has("Size") == true)&&(view.findViewById(R.id.item_Size)!=null)) {
                    ((TextView) view.findViewById(R.id.item_Size)).setText(colorSizeJson.optJSONObject(position).getString("Size"));
                    ((TextView) view.findViewById(R.id.item_Size)).setTextColor(color);
                }
                if ((colorSizeJson.optJSONObject(position).has("TotalNum") == true)&&(view.findViewById(R.id.item_TotalNum)!=null)) {
                    ((TextView) view.findViewById(R.id.item_TotalNum)).setText(colorSizeJson.optJSONObject(position).getString("TotalNum"));
                    ((TextView) view.findViewById(R.id.item_TotalNum)).setTextColor(color);
                }
                if ((colorSizeJson.optJSONObject(position).has("PlanNum") == true)&&(view.findViewById(R.id.item_PlanNum)!=null)) {
                    ((TextView) view.findViewById(R.id.item_PlanNum)).setText(colorSizeJson.optJSONObject(position).getString("PlanNum"));
                    ((TextView) view.findViewById(R.id.item_PlanNum)).setTextColor(color);
                }
                if ((colorSizeJson.optJSONObject(position).has("OwenNum") == true)&&(view.findViewById(R.id.item_OwenNum)!=null)) {
                    ((TextView) view.findViewById(R.id.item_OwenNum)).setText(colorSizeJson.optJSONObject(position).getString("OwenNum"));
                    ((TextView) view.findViewById(R.id.item_OwenNum)).setTextColor(color);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","ColorSizeListAdapter_position:"+position);
            return view;
        }
    }


    //获取明细
    private void GetPO(String paramDepart,String paramOrderNo,String paramStyleNo,String paramStyleSort,String paramManuDepartNo) {
        try {
            poJson=new JSONArray("[]");
            colorSizeJson=new JSONArray("[]");
            //显示明细数据
            if (poGrid!=null) {
                POGridAdapter poGridAdapter = new POGridAdapter(getContext());
                poGrid.setAdapter(poGridAdapter);
            }
            //显示明细数据
            if (colorsizeList!=null) {
                ColorSizeListAdapter colorSizeListAdapter = new ColorSizeListAdapter(getContext());
                colorsizeList.setAdapter(colorSizeListAdapter);
            }
            //执行SQL过程
            String SqlComm = "Exec KeyPoint_GetPO @ManuDepartNo='"+paramManuDepartNo+"',@Depart='" + paramDepart + "',@OrderNo='" + paramOrderNo + "',@StyleNo='" + paramStyleNo + "',@StyleSort='" + paramStyleSort
                    + "',@FormType='" + FormType + "',@DateNum=30, @OPERTYPE='PO',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //获取明细
    private void GetColorSize(String paramDepart,String paramOrderNo,String paramStyleNo,String paramStyleSort,String paramPO,String paramManuDepartNo) {
        try {
            colorSizeJson=new JSONArray("[]");
            //显示明细数据
            ColorSizeListAdapter colorSizeListAdapter=new ColorSizeListAdapter(getContext());
            colorsizeList.setAdapter(colorSizeListAdapter);
            //执行SQL过程
            String SqlComm = "Exec KeyPoint_GetSize @ManuDepartNo='"+paramManuDepartNo+"',@Depart='" + paramDepart + "',@OrderNo='" + paramOrderNo + "',@StyleNo='" + paramStyleNo + "',@StyleSort='" + paramStyleSort
                    + "',@PO='" + paramPO+ "',@FormType='" + FormType + "',@DateNum=120, @OPERTYPE='ColorSize',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //坏点记录根据类型显示不同界面
    private void MakeBadPoint(String paramClipType){
        if ((selDepartNo.length()==0)||(selStyleNo.length()==0)){
            curToast.setText("请先选择合约!");
            curToast.show();
            return;
        }
        Intent intentQuestionActivity=new Intent(getContext(),QuestionActivity.class);
        Bundle paramBundle1 = new Bundle();
        paramBundle1.clear();
        paramBundle1.putString("LoginUserNo", curLoginUserNo);
        paramBundle1.putString("LoginUser",curLoginUser);
        paramBundle1.putString("CurDepartNo",curDepartNo);
        paramBundle1.putString("CurDepart",curDepart);
        paramBundle1.putString("ServiceUrl",curServiceUrl);
        paramBundle1.putString("ServiceDir",curServiceDir);
        if (selDepart.length()==0) {
            selDepart=curDepart;
            selDepartNo=curDepartNo;
        }
        paramBundle1.putString("selDepart",selDepart);
        paramBundle1.putString("selDepartNo",selDepartNo);
        paramBundle1.putString("selImageFile",selImageFile);
        paramBundle1.putString("selStyleNo",selStyleNo);
        paramBundle1.putString("selOrderNo",selOrderNo);
        paramBundle1.putString("selStyleSort",selStyleSort);
        paramBundle1.putString("ClipType",paramClipType);
        paramBundle1.putString("TitleInv","疵点选择");
        paramBundle1.putString("NeedPos","YES");//图片标注
        paramBundle1.putInt("MaxPieces",MaxPieces);
        paramBundle1.putString("CPUID",CPUID);
        intentQuestionActivity.putExtras(paramBundle1);
        startActivityForResult(intentQuestionActivity,2000);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("requestCode:"+requestCode+" resultCode:"+resultCode);
        //选合约返回
        if ((requestCode==1000)&&(resultCode==1001)){
            //获取登陆参数
            Bundle paramBundle = data.getExtras();
            selDepart=paramBundle.getString("selDepart");
            selDepartNo=paramBundle.getString("selDepartNo");
            selOrderNo=paramBundle.getString("selOrderNo");
            selStyleNo=paramBundle.getString("selStyleNo");
            selStyleSort=paramBundle.getString("selStyleSort");
            selPO=paramBundle.getString("selPO");
            selColor=paramBundle.getString("selColor");
            selSize=paramBundle.getString("selSize");
            selPSXX=paramBundle.getString("selPSXX");
            selManuDepartNo=paramBundle.getString("selManuDepartNo");
            selManuDepart=paramBundle.getString("selManuDepart",selDepart);
            if (selManuDepart.length()==0) selManuDepart=selDepart;
            selImageFile=paramBundle.getString("selImageFile");
            //填充界面
            txt_OrderNo.setText(selOrderNo);
            txt_StyleNo.setText(selStyleNo);
            txt_StyleSort.setText(selStyleSort);
            txt_PO.setText(selPO);
            txt_Size.setText(selSize);
            txt_Color.setText(selColor);
            txt_Depart.setText(selManuDepart);
            txt_PSXX.setText(selPSXX);
        }
        hideBottomUIMenu();
    }



    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    //从字符串转颜色
    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor=Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }

    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                if (waitDialog.isShowing()==true) waitDialog.cancel();
                String tmpValue;
                //任意消息来均置焦点
                int msgId = msg.what;
                System.out.println("收到的消息是："+msg.what);
                try {
                    switch (msgId) {
                        case MSG_AuthorMSG:
                            System.out.println("MSG_AuthorMSG--1:");
                            Bundle bundle=msg.getData();
                            System.out.println("MSG_AuthorMSG--2:"+bundle);
                            if (bundle.getString("Result","N").equals("Y")){
                                if (popupWindow != null && popupWindow.isShowing()) popupWindow.dismiss();
                                //根据需要进的功能调用对应模块
                                if (bundle.getString("FuncName","").equals("AffirProc")) showAffirmActivity();
                                if (bundle.getString("FuncName","").equals("ArrangeProc")) showProcActivity();
                                if (bundle.getString("FuncName","").equals("DaliyAccount")) showWorkActivity();
                            } else{
                               String resultinfo=bundle.getString("ResultInfo","操作有误");
                                AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                                        .setTitle("系统提示").setMessage(resultinfo)
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                hideBottomUIMenu();
                                                return;
                                            }
                                        }).create(); // 创建对话框
                                alertDialog.show(); // 显示对话框
                            }
                            break;

                        case MSG_ERRMSG:
                            Bundle bundle1=msg.getData();
                            String mesg=bundle1.getString("MSG","");
                            curToast.setText(mesg);
                            curToast.show();
                        case msgFocusBarcode:
                            setEditBarcodeFocus();
                            break;
                        case MSG_SCANBARCODE:

                            setEditBarcodeFocus();
                            fillFormtext();
                            break;
                        case MSG_HeadOver:
                            CreateListHead();
                            break;
                        case MSG_GetDetail:
                            GetDetail("WorkDetail",FormType);
                            break;
                        case MSG_DetailOver:
                            //显示明细数据
                            if (detailList!=null) {
                                DetailListAdapter detailListAdapter = new DetailListAdapter(getContext());
                                detailList.setAdapter(detailListAdapter);
                            }
                            break;
                        case MSG_ChartOver:
                            showBalanceChart();
                            break;
                        case MSG_POOver:
                            selectPO();
                            break;
                        case MSG_ColorSizeOver:
                            //显示明细数据
                            if (colorsizeList!=null) {
                                ColorSizeListAdapter colorSizeListAdapter = new ColorSizeListAdapter(getContext());
                                colorsizeList.setAdapter(colorSizeListAdapter);
                            }
                            break;
                        default:
                            break;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    };

    //获取明细数据
    private void GetDetail(String paramType,String paramFormName) {
        String sqlcmd="Exec KeyPoint_CustomGetDetail @OperType='Detail',@QueryType='"+paramType+"',@FormName='"+paramFormName
                +"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlcmd);
    }


    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println(SQLComm);
        Runnable run = new Runnable() {
            @Override
            public synchronized void run() {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    reentrantLock.lock();
                    System.out.println("任务开始：" + df.format(System.currentTimeMillis()));
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    //往界面转数据;
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        System.out.println(jsonArray);
                        String OPERTYPE = "";
                        if (jsonArray.optJSONObject(0).has("OPERTYPE") == true)
                            OPERTYPE = jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (jsonArray.optJSONObject(0).has("OperType") == true)
                            OPERTYPE = jsonArray.optJSONObject(0).getString("OperType");
                        if (OPERTYPE.toUpperCase().equals("SCANBARCODE") || OPERTYPE.toUpperCase().equals("AffirmTrans".toUpperCase())) {
                            resultJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_SCANBARCODE;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("HEAD")) {
                            headJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_HeadOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("DETAIL")) {
                            detailJson = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_DetailOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("CHART")) {
                            chartJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_ChartOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("PO")) {
                            poJson = jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_POOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("COLORSIZE")) {
                            colorSizeJson = jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_ColorSizeOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("AuthorCheck".toUpperCase())) {
                            //显示预排单;
                            resultJSON = jsonArray;
                            Message msg = new Message();
                            msg.what = MSG_AuthorMSG;
                            Bundle bundle = new Bundle();
                            if (resultJSON.optJSONObject(0).has("FuncName"))
                                bundle.putString("FuncName", resultJSON.optJSONObject(0).getString("FuncName"));
                            if (resultJSON.optJSONObject(0).has("Result"))
                                bundle.putString("Result", resultJSON.optJSONObject(0).getString("Result"));
                            if (resultJSON.optJSONObject(0).has("ResultInfo"))
                                bundle.putString("ResultInfo", resultJSON.optJSONObject(0).getString("ResultInfo"));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("ChangePsw".toUpperCase())) {
                            //显示预排单;
                            resultJSON = jsonArray;
                            Message msg = new Message();
                            msg.what = MSG_AuthorMSG;
                            Bundle bundle = new Bundle();
                            if (resultJSON.optJSONObject(0).has("Result"))
                                bundle.putString("Result", resultJSON.optJSONObject(0).getString("Result"));
                            if (resultJSON.optJSONObject(0).has("ResultInfo"))
                                bundle.putString("ResultInfo", resultJSON.optJSONObject(0).getString("ResultInfo"));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        //SQL异常;
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle = new Bundle();
                            bundle.putString("MSG", jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }
                    } else {
                        //显示预排单;
                        //关闭ProgressDialog
                        Message msg = new Message();
                        msg.what = MSG_ERRMSG;
                        Bundle bundle = new Bundle();
                        bundle.putString("MSG", "未返回任何数据!");
                        msg.setData(bundle);
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //显示预排单;
                    Message msg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("MSG", e.getMessage());
                    msg.setData(bundle);
                    msg.what = MSG_ERRMSG;
                    fragmentHandler.removeMessages(msg.what);
                    fragmentHandler.sendMessage(msg);
                    reentrantLock.unlock();
                }finally {
                    reentrantLock.unlock();
                }
                AllowScan=true;
                System.out.println("任务完成：" + df.format(System.currentTimeMillis()));

            }
        };
        Thread thread1 = new Thread(run, "SyncThreadSQL");
        thread1.start();
    }



    //打开数据库
    public void OpenCreateDB(){
        if (tmpdb==null) {
            MainActivity activity = (MainActivity) getActivity();
            tmpdb = activity.mainDB;
        }
    }


    //清除界面显示内容
    private void clearFormText(){
        txt_HintInfo.setText("");
        txt_OrderNo.setText("");
        txt_StyleNo.setText("");
        txt_PO.setText("");
        txt_Color.setText("");
        txt_Size.setText("");
        txt_StyleSort.setText("");
        txt_PSXX.setText("");
        txt_HintInfo.setText("");
    }

    //填充界面显示内容;
    private void fillFormtext(){
        if (resultJSON.length()>0)
        {
            try {
                //别的参数刷新
                if (resultJSON.getJSONObject(0).has("OrderNo")==true) txt_OrderNo.setText(resultJSON.getJSONObject(0).getString("OrderNo"));
                if (resultJSON.getJSONObject(0).has("StyleNo")==true) txt_StyleNo.setText(resultJSON.getJSONObject(0).getString("StyleNo"));
                if (resultJSON.getJSONObject(0).has("PO")==true) txt_PO.setText(resultJSON.getJSONObject(0).getString("PO"));
                if (resultJSON.getJSONObject(0).has("Color")==true) txt_Color.setText(resultJSON.getJSONObject(0).getString("Color"));
                if (resultJSON.getJSONObject(0).has("Size")==true) txt_Size.setText(resultJSON.getJSONObject(0).getString("Size"));
                if (resultJSON.getJSONObject(0).has("StyleSort")==true) txt_StyleSort.setText(resultJSON.getJSONObject(0).getString("StyleSort"));
                if (resultJSON.getJSONObject(0).has("Depart")==true) txt_Depart.setText(resultJSON.getJSONObject(0).getString("Depart"));
                if (resultJSON.getJSONObject(0).has("PSXX")==true) txt_PSXX.setText(resultJSON.getJSONObject(0).getString("PSXX"));
                if (resultJSON.getJSONObject(0).has("DBH")==true) txt_DBH.setText(resultJSON.getJSONObject(0).getString("DBH"));
                if (resultJSON.getJSONObject(0).has("Barcode")==true) txt_Barcode.setText(resultJSON.getJSONObject(0).getString("Barcode"));
                if (resultJSON.getJSONObject(0).has("Number")==true) txt_Number.setText(resultJSON.getJSONObject(0).getString("Number"));
                if (resultJSON.getJSONObject(0).has("ScanNum")==true) txt_ScanNum.setText(resultJSON.getJSONObject(0).getString("ScanNum"));
                if (resultJSON.getJSONObject(0).has("OwenNum")==true) txt_OwenNum.setText(resultJSON.getJSONObject(0).getString("OwenNum"));
                if (resultJSON.getJSONObject(0).has("TodaySewNum")==true) txt_TodaySewNum.setText(resultJSON.getJSONObject(0).getString("TodaySewNum"));

                if (resultJSON.getJSONObject(0).has("LoadDetail")==true) {
                    if (resultJSON.getJSONObject(0).getString("LoadDetail").toUpperCase().equals("YES")) GetDetail("WorkDetail",FormType);
                }

                if (resultJSON.getJSONObject(0).has("HintInfo")==true) txt_HintInfo.setText(resultJSON.getJSONObject(0).getString("HintInfo"));
                if (resultJSON.getJSONObject(0).has("ResultInfo")==true) txt_HintInfo.setText(resultJSON.getJSONObject(0).getString("ResultInfo"));
                if (resultJSON.getJSONObject(0).has("ErrInfo")==true)
                {
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle("系统提示").setMessage(resultJSON.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideBottomUIMenu();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


    }

    //自定义适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_query_listhead, null, false);
            //if (convertView == null) convertView = inflater.inflate(R.layout.activity_query_listhead, null, false);
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            int backcolor = getResources().getColor(R.color.content);
            if (position%2==0) view.setBackgroundColor(backcolor);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (detailJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = detailJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                for (int i = 0; i < headJson.length(); i++)
                    if (headJson.optJSONObject(i).has("TitleText") == true) {
                        try {
                            String TitleName = headJson.optJSONObject(i).getString("TitleName");
                            if (detailJson.optJSONObject(position).has(TitleName)==true) tmpValue= detailJson.optJSONObject(position).getString(TitleName);
                            else tmpValue="unReturn";
                            int TxtSize = headJson.optJSONObject(i).getInt("TxtSize");
                            float txtWidth = headJson.optJSONObject(i).getLong("TxtWidth");
                            int AutoZoom = headJson.optJSONObject(i).getInt("AutoZoom");
                            TextView tv = new TextView(view.getContext());
                            tv.setText(tmpValue);
                            tv.setWidth((int) txtWidth);
                            tv.setTextColor(color);
                            tv.setGravity(Gravity.CENTER_VERTICAL);
                            if (headJson.optJSONObject(i).has("Align")==true) {
                                int Align;
                                Align = headJson.optJSONObject(i).getInt("Align");
                                switch (Align) {
                                    case 0:
                                        tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                        break;
                                    case 1:
                                        tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                        break;
                                    case 2:
                                        tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                        break;
                                    default:
                                        tv.setGravity(Gravity.CENTER_VERTICAL);
                                        break;
                                }
                            }
                            //自定义文字颜色;
                            if (headJson.optJSONObject(i).has("Color")==true){
                                tv.setTextColor(GetColorValue( headJson.optJSONObject(i).getString("Color")));
                            }
                            //自定负数是红色;
                            if ((headJson.optJSONObject(i).has("NgvColor")==true)&&(headJson.optJSONObject(i).has("NgvTrans")==true)){
                                if (headJson.optJSONObject(i).getString("NgvTrans").equals("YES")&&(isNumer(tmpValue)==true)){
                                    if (Float.valueOf(tmpValue)<0) tv.setTextColor(GetColorValue(headJson.optJSONObject(i).getString("NgvColor")));
                                }
                            }
                            tv.setTextSize(TxtSize);
                            //添加到View中;
                            if (AutoZoom == 1)
                                ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                            else ((LinearLayout)view).addView(tv);
                            //增加间隔线
                            if (i<headJson.length()-1) {
                                View lineView = new View(view.getContext());
                                lineView.setBackgroundColor(getResources().getColor(R.color.gridLine));
                                ((LinearLayout)view).addView(lineView, new LinearLayout.LayoutParams(1, MATCH_PARENT, 0));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailListAdapter_position:"+position);
            return view;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        curActive=true;
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        setEditBarcodeFocus();
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }

    @Override
    public void onPause() {
        super.onPause();
        curActive=false;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        curActive=!hidden;
        //读配置文件
        System.out.println("curActive:"+curActive);
    }
}
